import {fetch, post} from '../../../utils/axios'

const state = {
  name: '文件替换',
  host: {items: [{ text: '', value: '' }]},
  fields: {},
  hostRules: [
    (v) => !v.length < 1 || '请选择主机'
  ],
  info: [],
  count: 0,
  interval: '',
  active: null,
  show: true,
  vcodeDialog: false,
  verifyTitle: '非特殊情况不建议使用此功能，若要强行使用，请输入验证码'
}

const mutations = {
  loadSelect (state, payload) {
    fetch('/publisher/get_host/', {
      project: payload
    }).then((response) => {
      state.fields.host = []
      state.host = {items: [{ text: '', value: '' }]}
      let res = JSON.parse(response)
      state.host.items = res.data
    }).catch((error) => {
      state.etext = error.response
    })
  },
  openVerify (state) {
    state.vcodeDialog = true
  },
  fileReplace (state, payload) {
    if (state.fields.host.length > 0) {
      post('/publisher/file_replace/', {
        opt: payload,
        hosts: state.fields.host
      }).then((response) => {
        alert(response)
        state.vcodeDialog = false
      }).catch((error) => {
        alert(error.response.data)
      })
    } else {
      alert('请选择主机！')
    }
  },
  loadReplaceInfo (state, payload) {
    let url = '/publisher/file_replace_info/'
    post(url, {
      opt: payload
    }).then((response) => {
      state.info = JSON.parse(response).info
      state.count = response.count
    }).catch((error) => {
      alert(error.response.data)
    })
  }
}

const actions = {
  loadSelect ({commit}, payload) {
    commit('loadSelect', payload)
  },
  fileReplace ({commit}, payload) {
    commit('fileReplace', payload)
  },
  loadReplaceInfo ({commit}, payload) {
    state.interval = setInterval(() => {
      commit('loadReplaceInfo', payload)
    }, 2000)
  },
  openVerify ({commit}) {
    commit('openVerify')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
